<script setup lang="ts">
import { ref, onMounted,nextTick, watch, toRaw, reactive } from 'vue'
import { useRouter } from "vue-router";
import { PictureOutlined, LoadingOutlined, ExclamationCircleOutlined } from '@ant-design/icons-vue';
import { teachLiveCreate, teachLiveLast } from '../stores/api/live'
import type { UploadProps } from 'ant-design-vue';
import { message } from 'ant-design-vue';
import { useCounterStore } from '../stores/counter'
import type { UnwrapRef } from 'vue';
import type { Rule } from 'ant-design-vue/es/form';
import {upload} from '../utils/upload' // 引入js
import { ImgUrlPrefix } from '../utils/config'
import clipboard3 from 'vue-clipboard3'
// defineProps<{ msg: string }>()
const props:any = defineProps({
    // 触发滚动的容器
    isShow: {
      type: [Boolean],
      default: false
    },
    info: {
        type: [Object],
        default: {}
    },
    secret_name: {
        type: [Object],
        default: {}
    }
})
const emits = defineEmits(['backChange'])
const router:any = useRouter()
const fileList = ref([]);
const uploading = ref<boolean>(false);
const imageUrl = ref<string>('');
const secret = ref<string>('') // 腾讯云请求创建直播流
const info = ref({})
const liveInfo:any = ref({})
const isShowModel = ref(false)
const store = useCounterStore()
const { toClipboard } = clipboard3()

interface FormState {
  title: string;
  permission: Number | undefined;
  thumbnail: string;
  status_at: string | Number,
  type: string | Number
}
const formRef = ref();
const labelCol = { span: 5 };
const wrapperCol = { span: 24 };
const formState: UnwrapRef<FormState> = reactive({
  title: '',
  permission: undefined,
  thumbnail: '',
  status_at: '', // 开播时间
  type: '' // 开播状态
});
const rules: Record<string, Rule[]> = {
  title: [
    { required: true, message: '请输入直播标题', trigger: 'change' },
  ],
  permission: [{ required: true, message: '请选择权限', trigger: 'change' }]
};
// 提交
const onSubmit = () => {
  formRef.value
    .validate()
    .then(() => {
      console.log('values', formState, toRaw(formState));
      createLive()
    })
    .catch(error => {
      console.log('error', error);
    });
};
// 取消
const resetForm = () => {
  formRef.value.resetFields();
  imageUrl.value = ''
  emits("backChange", { isShow: false});
};

// 去直播
const goLive = () => {
    // userWebsocket.sendMsg(JSON.stringify({content: 'hello'}))
    // createLive()
    lastLiveInfo()
}

// 上一次直播信息
const lastLiveInfo = () => {
    teachLiveLast({}, 'post').then((res: any) => {
        console.log(res)
        if (res.code == 200) {
            info.value = res.data
            // 判断上一次直播信息
            if(res.data.status == 10) {
                router.push({path: '/live', query: { isGain: true}})
            } else {
                createLive()
            }
        }
    }).catch((err: any) => {
        console.log(err)
    })
}
// 调用创建直播间接口
const createLive = () => {
    let obj = {
        "title":formState.title,
        "thumbnail":formState.thumbnail,
        "permission": formState.permission, // 10所有人 20会员
        "status_at": formState.type == 20 ? store.getTimestamp(formState.status_at) : formState.type  // 立即开播--0 预热开播--时间戳
    }
    console.log(obj)
    teachLiveCreate(obj, 'post').then((res: any) => {
        console.log(res)
        if(res.code == 200) {
            secret.value = res.data.secret
            message.success('创建成功');
            emits("backChange", { isShow: false});
            formState.title = ''
            formState.thumbnail = ''
            formState.type = ''
            formState.status_at = ''
            imageUrl.value = ''
            formState.permission = undefined
            liveInfo.value = res.data
            if(res.data.status != 20) {
               isShowModel.value = true
            }
        } else {
            message.error(res.message);
        }
    }).catch((err: any) => {
        console.log(err)
    })
}

// 图片地址拼接
const getImgUrl = (val) => {
    const url = ImgUrlPrefix(val)
    return url
}
// 取直播间
const onSubmit2 = () => {
    router.push({path: '/live', query: { isGain: false, liveInfo: JSON.stringify(liveInfo.value)}})
}
// 取消
const resetForm2 = () => {
  isShowModel.value = false
}
// 图片上传--删除
const handleRemove: UploadProps['onRemove'] = file => {
  const index = fileList.value.indexOf(file);
  const newFileList = fileList.value.slice();
  newFileList.splice(index, 1);
  fileList.value = newFileList;
  imageUrl.value = ''
};
// 图片上传之前
const beforeUpload: UploadProps['beforeUpload'] = file => {
  fileList.value = [...(fileList.value || []), file];
  console.log(fileList.value)
  return true;
};
// 图片上传
const handleUpload = (data) => {
//   const formData = new FormData();
//   fileList.value.forEach((file: UploadProps['fileList'][number]) => {
//     formData.append('files[]', file as any);
//   });
  uploading.value = true;
  console.log(fileList.value, data,'handleUpload')
  upload(data.file,res => {
      console.log(res,'ddddd')
      if(res) {
            const startIndex = res.indexOf('/') + 1;
            const urls = res.substring(startIndex);
            formState.thumbnail = urls
            imageUrl.value = getImgUrl(urls)
            console.log(urls)
      }
      uploading.value = false;
  })
};

//复制
const copy = async (text) => {
  try {
    await toClipboard(text);
    message.success('复制成功');
  } catch (error) {
    console.error(error);
  }
}
// 监听消息
watch(() => props.info, (newVal:any, oldValue) => {
   console.log('infoData',newVal, oldValue)
   formState.title = newVal.title
   formState.permission = newVal.permission
   formState.thumbnail = newVal.thumbnail
   formState.type = newVal.status_at == 0 ? newVal.status_at : 20
   formState.status_at = store.timestampChangDate(newVal.status_at * 1000)
//    formState.status = newVal.status != 0 ? newVal.status : ''
   imageUrl.value = getImgUrl(newVal.thumbnail)
})
watch(() => props.secret_name, (newVal:any, oldValue) => {
   console.log('secret_name',newVal, oldValue)
   if(newVal) {
      isShowModel.value = true
      liveInfo.value = newVal
   }
})

onMounted(() => {

});
</script>

<template>
  <div class="start-live-room">
    <a-modal v-model:open="props.isShow" title="创建直播间" ok-text="开始直播" cancel-text="取消" @cancel="resetForm" :footer="null">
        <div class="live-left">
            <a-form
                ref="formRef"
                :model="formState"
                :rules="rules"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-item ref="title" label="直播标题" name="title">
                      <a-input v-model:value="formState.title" class="input-item-dd" placeholder="请输入直播间标题" />
                </a-form-item>
                <a-form-item label="权限" name="permission">
                    <a-select v-model:value="formState.permission" placeholder="请选择权限">
                        <a-select-option :value="10">所有人</a-select-option>
                        <a-select-option :value="20">会员</a-select-option>
                    </a-select>
                </a-form-item>
                <a-form-item name="type" label="开播状态">
                    <a-radio-group v-model:value="formState.type" name="radioGroup">
                        <a-radio :value="0">立即开播</a-radio>
                        <a-radio :value="20">直播预告</a-radio>
                    </a-radio-group>
                </a-form-item>
                <a-form-item name="status_at" label="开播时间" v-if="formState.type == 20">
                    <a-date-picker
                        style="margin-top:0px"
                        v-model:value="formState['status_at']"
                        :disabled-date="store.disabledDate"
                        :disabled-time="store.disabledDateTime"
                        show-time
                        showNow
                        placeholder="请选择时间"
                        format="YYYY-MM-DD HH:mm:ss"
                        value-format="YYYY-MM-DD HH:mm:ss"
                    />
                </a-form-item>
                <a-form-item label="封面图" name="thumbnail">
                    <a-upload   class="cover-g" name="avatar" list-type="picture-card" :show-upload-list="false" :file-list="fileList" :before-upload="beforeUpload" @remove="handleRemove" :customRequest="handleUpload">
                        <!-- <img v-if="imageUrl" :src="imageUrl" alt="" /> -->
                        <div v-if="imageUrl" class="cover-image">
                            <img v-if="imageUrl" :src="imageUrl" alt="" />
                        </div>
                        <div v-else>
                            <loading-outlined v-if="uploading"></loading-outlined>
                            <PictureOutlined v-else :style="{fontSize: '22px'}" />
                            <div class="ant-upload-text">上传封面</div>
                        </div>
                    </a-upload>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: right;">
                    <a-button class="btn-ss" type="primary" @click="onSubmit">开始直播</a-button>
                    <a-button style="margin-left: 10px" @click="resetForm">取消</a-button>
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
    <a-modal v-model:open="isShowModel" title="直播信息"  ok-text="" cancel-text="" @cancel="resetForm2" :footer="null">
        <div>
            <a-form
                ref="formRef"
                :label-col="labelCol"
                :wrapper-col="wrapperCol"
            >
                <a-form-item ref="title" label="服务器：" name="server">
                     <div>{{liveInfo.server}} <a-tag color="default" @click="copy(liveInfo.server)">复制</a-tag></div>
                </a-form-item>
                <a-form-item ref="title" label="推流码" name="secret">
                     <div>{{liveInfo.secret}} <a-tag color="default" @click="copy(liveInfo.secret)">复制</a-tag></div>
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }">
                    <ExclamationCircleOutlined style="color: red" /> 推流码 30分钟有效
                </a-form-item>
                <a-form-item :wrapper-col="{ span: 24, offset: 4 }" style="text-align: right;">
                    <a-button class="btn-ss" type="primary" @click="onSubmit2">进入直播间</a-button>
                    <a-button style="margin-left: 10px" @click="resetForm2">取消</a-button>
                </a-form-item>
            </a-form>
        </div>
    </a-modal>
  </div>
</template>

<style scoped>
.start-live-room{
   display: flex;
   color: #333;
   background-color: rgba(22,24,35,1);
}
.live-left{
   flex: 3;
   /* height: 93vh; */
   /* position: relative; */
   overflow: hidden;
   padding:0 15px;
}
.live-video{
  width: 100%;
  height: 100%;
  object-fit: cover; /* 确保视频撑满父容器 */
}
.basic-info{
    display: flex;
    color: #999;
}
.cover-img{
    width: 50px;
    border-radius: 8px;
}
.cover-g{
    /* background-color: rgb(51,52,63); */
    width: 130px;
    height: 132px;
    line-height: 26px;
    text-align: center;
    padding: 10px 0;
    border-radius: 10px;
}
.cover-image{
    width: 100%;
    height: 100%;
}
.cover-image img{
    width: 100%;
    height: 100%;
}
.input-item-dd{
    /* height: 30px; */
    /* padding-top: 0; */
    /* background-color: transparent; */
    font-size: 14px; /* 占位符字体大小 */
    /* border:none; */
    /* outline: none; */
    color: #000;
}
.input-item-dd::placeholder {
  font-size: 14px; /* 占位符字体大小 */
  color: #999; /* 占位符字体颜色 */
}
.type-item{
  padding-left:10px;
  margin-top: 20px;
}
.type-s{
    padding: 5px 15px;
    margin-right: 10px;
    border-radius: 10px;
    cursor: pointer;
}
.active{
    background-color: rgb(51,52,63);
}

.positin-boottom{
    position: absolute;
    bottom: 10px;
    width: 94%;
}
.bottom-item-a{
    width:100%;
   display: flex;
   justify-content: space-between;
   align-items: center;
   color: #fff;
   background-color: #080808;
   padding: 8px 15px;
   border-radius: 10px;
}
.btn-ss{
    background-color: #fe5d26;
    height: 34px;
}
.btn-ss:hover{
    background-color: #fe5d26;
}
.live-right{
    color: #fff;
   flex:1;
   position:relative;
   /* background-color: rgb(37,38,50); */
   padding-right: 15px;
}
.live-right-list{
    background-color: rgb(51,52,63);
    padding: 10px 20px;
    height: 22vh;
    border-radius: 10px;
    overflow-y: auto;
}
.live-item{
   display: flex;
   align-items: center;
   justify-content: center;
   color: #898687;
   margin-top: 10px;
}
.live-num{
    line-height: 30px;
    margin-bottom: 20px;
}
.ranking{
    margin-right: 30px;
}
.nick-name{
    margin:0 20px 0 10px;
}
.img-avatar{
    width: 35px;
    height: 35px;
    border-radius: 50%;
}
.grade{
    width: 30px;
}

.live-message{
    padding: 10px 20px;
    background-color: rgb(37,38,50);
    height: 70vh;
    overflow-y: auto;
}
.msg-item{
    display: flex;
    align-items: flex-start;
    margin-top: 8px;
}
.msg-grade{
    width: 40px;
}
.name{
 color: #8ce7ff;
 margin:0 10px;
}
.msg-content{
    line-height: 25px;
}
.bottom-contt{
    position: absolute;
    bottom: 0;
    width: 100%;
    /* background-color: rgb(37,38,50); */
}
.bottom-send{
    display: flex;
    align-items: center;
    color: #fff;
    background-color: rgb(65,66,76);
    margin: 10px 15px 10px 0;
    padding: 8px;
    border-radius: 10px;
}
.send-input{
    background-color: rgb(65,66,76);
    font-size: 16px; /* 占位符字体大小 */
    border:none;
    color: #fff;
}
.send-input::placeholder {
  font-size: 14px; /* 占位符字体大小 */
  color: #999; /* 占位符字体颜色 */
}
.read-the-docs {
  color: #888;
}
</style>